package com.xgst.lib.http

import com.blankj.utilcode.util.LogUtils
import com.xgst.lib.utils.UnicodeUtils
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import java.nio.charset.Charset

class LogInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val requestBody = request.body
        var body = ""
        if(requestBody != null){
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            val contentType = requestBody.contentType()
            val charset: Charset = contentType?.charset(Charsets.UTF_8) ?: Charsets.UTF_8
            body = buffer.readString(charset)
        }
        val path = request.url.encodedPath

        //获取返回数据，如果网络或者服务器异常，导致没有返回数据，那么下面的代码不会执行
        val response = chain.proceed(request)
        val responseBody = response.body!!
        val source = responseBody.source()
        source.request(Long.MAX_VALUE)
        var buffer = source.buffer
        val contentType = responseBody.contentType()
        val charset: Charset = contentType?.charset(Charsets.UTF_8) ?: Charsets.UTF_8
        var resultString = buffer.clone().readString(charset)

        if(!path.contains("window/windowStatistics")){
            if(body.contains("image/*") && body.length > 150){
                val arr = body.split("\n")
                if(arr.size > 3){
                    body = "上传图片，截取部分信息：\n${arr[1]}\n${arr[2]}\n${arr[3]}"
                }
            }
            body = UnicodeUtils.unicodeToUTF_8(body)
            resultString = UnicodeUtils.unicodeToUTF_8(resultString)
            LogUtils.i("接口地址：${request.url}","\n请求参数: $body","\n返回结果：$resultString")
        }
        return response
    }
}